package main

import (
	"os"

	"gitee.com/go-wena/cli"
	"gitee.com/go-wena/wena"
	"gitee.com/go-wena/wena/internal/builder"
	"gitee.com/go-wena/wena/internal/git"
)

func init() {
	build("run").AddTo(root)
	build("build").AddTo(root)
}

func build(use string) *cli.Command {
	g := builder.New()
	var comment string
	if use == "run" {
		comment = "编译并运行"
	} else {
		comment = "仅编译"
	}

	var watch bool
	var gitRepo string
	var src = "."

	return cli.New(
		cli.Use(use),
		cli.Comment(comment, use+" wena app", comment),
		cli.Flags(g.ApplyToFlagSet),
		cli.Flags(func(fs *cli.FlagSet) {
			fs.BoolVarP(&watch, "watch", "w", watch, "监听文件改动")
			fs.StringVar(&gitRepo, "git.repo", gitRepo, "git repo")
			fs.StringVarP(&src, "src", "s", src, "源码目录")
		}),
		cli.Run(func(c *cli.Command, args []string) {
			if gitRepo != "" {
				src, _ = os.MkdirTemp("", "*")
				_, err := git.Clone(c.Context(), src, false, &git.CloneOptions{URL: gitRepo})
				cli.CheckErr(err)
			}

			e, err := wena.New(src, g)
			cli.CheckErr(err)
			isRun := use == "run"
			if watch && isRun {
				err = e.Watch(c.Context(), true)
			} else {
				err = e.Build(c.Context(), isRun)
			}
			cli.CheckErr(err)
		}),
	)
}
